package com.ruoyi.consumer.controller.wallet;

import com.ijpay.core.enums.SignType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.model.RefundModel;
import com.jfinal.kit.StrKit;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.consumer.domain.WxConfig;
import com.ruoyi.consumer.domain.pay.JsApiOrderModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class RefundService {
    @Autowired
    private WxConfig wxConfig;

    public AjaxResult processRefund(String orderNumber, Integer Totalfee, Integer refundFee) {
        JsApiOrderModel jsApiOrderModel = new JsApiOrderModel();
        jsApiOrderModel.setOut_trade_no(orderNumber);
        jsApiOrderModel.setTotal_fee(Totalfee.toString());
        jsApiOrderModel.setRefund_fee(refundFee.toString());
        try {
            if (StrKit.isBlank(orderNumber)) {
                return AjaxResult.success("transactionId、out_trade_no二选一");
            }
            Map<String, String> params = RefundModel.builder()
                    .appid(wxConfig.getAppid())
                    .mch_id(wxConfig.getMchid())
                    .nonce_str(WxPayKit.generateStr())
                    .out_trade_no(orderNumber)
                    .out_refund_no(WxPayKit.generateStr())
                    .total_fee(Totalfee.toString())
                    .refund_fee(refundFee.toString())
                    .build()
                    .createSign(wxConfig.getMchKey(), SignType.MD5);
            String refundStr = WxPayApi.orderRefund(false, params, "/root/cert/apiclient_cert.p12", wxConfig.getMchid());
//            String refundStr = WxPayApi.orderRefund(false, params, "D:/cert/apiclient_cert.p12", wxConfig.getMchid());
            return AjaxResult.success(refundStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
